{extend name="layout/iframe" /}

{block name="content"}
<form class="layui-form">
    <blockquote class="layui-elem-quote news_search">
        <!--<div class="layui-inline">
            <input type="checkbox" name="selectAll" id="selectAll" lay-filter="selectAll" lay-skin="primary" title="全选">
        </div>
        <div class="layui-inline">
            <a class="layui-btn layui-btn-sm layui-btn-danger batchDel">批量删除</a>
        </div>-->
        <div class="layui-inline" id="upload-image">
            <a class="layui-btn layui-btn-sm upload-file" id="upload-btn" data-multi="true">上传报告</a>
        </div>
    </blockquote>

    <ul class="layer-photos-demo" id="Images"></ul>
</form>

<input type="hidden" class="datalist_url" value="{:url('admin/product/getdetections')}">
{/block}

{block name="pagescript"}
<script src="__STATIC__/admin/js/qiniu/plupload.full.min.js" type="text/javascript"></script>
<script src="__STATIC__/admin/js/qiniu/qiniu.js" type="text/javascript"></script>
<script src="__STATIC__/admin/js/qiniu/qiniuConfig.js" type="text/javascript"></script>

<script type="text/javascript">
    layui.use(['form', 'layer', 'flow'], function(){

        var form = layui.form,
            layer = parent.layer === undefined ? layui.layer : top.layer,
            $ = layui.jquery,
            flow = layui.flow;

        var datalist_url = $('.datalist_url').val();


        /*if ($(parent.window.frames[0].document).find('input[name=id]').val()) {
            datalist_url += '?id=' + $(parent.window.frames[0].document).find('input[name=id]').val();
        } else {
            datalist_url += '?detections=' + $(parent.window.frames[0].document).find('.detections').val();
        }*/
        datalist_url += '?detections=' + $(parent.window.frames[0].document).find('.detections').val();
        // 流加载图片
        var imgNums = 20;  //单页显示图片数量
        flow.load({
            elem: '#Images', //流加载容器
            done: function(page, next){ //加载下一页
                console.log(page);
                $.post(
                    datalist_url,
                    {
                        'page': page,
                        'limit': imgNums
                    },
                    function(res){
                        // 插入数据
                        var imgList = [],
                            data = res.data;
                        var length = data.length;
                        setTimeout(function(){
                            for(var i = 0; i < length; i++){
                                var html = '';
                                html += '<li class="layer-img">';
                                    html += '<a href="'+ data[i].img_url +'" target="_blank"><img layer-src="'+ data[i].img_url +'" src="'+ data[i].img_url +'" alt="图片" ></a>';
                                    html += '<div class="operate">';
                                    html += '<div class="check"><input type="checkbox" name="detection_img" lay-filter="choose" lay-skin="primary" title=""></div>';
                                    html += '<i class="layui-icon img_del">&#xe640;</i>';
                                    html += '</div>';
                                html += '</li>';
                                imgList.push(html);
                            }
                            next(imgList.join(''), page < (res.count/imgNums));

                            // 设置图片的高度
                            $("#Images li img").height($("#Images li img").width());
                            form.render();
                        }, 500);
                    }
                );
            }
        });

        // 全选
        /*form.on('checkbox(selectAll)', function(data){
            var child = $("#Images li input[type='checkbox']");
            child.each(function(index, item){
                item.checked = data.elem.checked;
            });
            form.render('checkbox');
        });*/

        // 通过判断是否全部选中来确定全选按钮是否选中
        /*form.on("checkbox(choose)",function(data){
            var child = $(data.elem).parents('#Images').find('li input[type="checkbox"]');
            var childChecked = $(data.elem).parents('#Images').find('li input[type="checkbox"]:checked');
            if(childChecked.length == child.length){
                $(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = true;
            }else{
                $(data.elem).parents('#Images').siblings("blockquote").find('input#selectAll').get(0).checked = false;
            }
            form.render('checkbox');
        });*/

        // 批量删除
        /*$(".batchDel").click(function(){
            var $checkbox = $('#Images li input[type="checkbox"]');
            var $checked = $('#Images li input[type="checkbox"]:checked');
            if($checkbox.is(":checked")){
                layer.confirm('确定删除选中的图片？',{icon:3, title:'提示信息'},function(index){
                    var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                    setTimeout(function(){
                        //删除数据
                        $checked.each(function(){
                            $(this).parents("li").hide(1000);
                            setTimeout(function(){$(this).parents("li").remove();},950);
                        });
                        $('#Images li input[type="checkbox"],#selectAll').prop("checked",false);
                        form.render();
                        layer.close(index);
                        layer.msg("删除成功");
                    },2000);
                })
            }else{
                layer.msg("请选择需要删除的图片");
            }
        });*/


        /*// 相册层
        $("body").on("click", "#Images img",function(){
            layer.photos({
                photos: '.layer-img',
                anim: 5
            });
        });*/

        var UploadFile = function() {

            var upload_element = 'upload-image'; // 上传按钮的上级元素ID
            var upload_btn = 'upload-btn'; // 上传按钮的ID
            var field = $('#' + upload_btn).attr('data-field');
            var token_url = $('.token_url').val();
            var record_url = $('.record_url').val();
            var max_file_size = $('#' + upload_btn).attr('data-max_file_size');
            var extensions = $('#' + upload_btn).attr('data-extensions');
            var multi = $('#' + upload_btn).attr('data-multi');
            var isAjax = $('#' + upload_btn).attr('data-ajax');


            /**
             * 七牛初始化
             */
            var initUploader = function () {
                var url = "";
                var qiniupercent = "";
                var uploader = upload_element;
                var pickfiles = upload_btn;

                if($('#' + uploader).length <= 0){
                    return;
                }

                if(extensions == '' || extensions == undefined){
                    extensions = 'jpg,jpeg,gif,png';
                }
                if(multi == 'false'){
                    multi = false;
                    if(max_file_size == '' || max_file_size == undefined){
                        max_file_size = '500kb';
                    }
                }else{
                    multi = true;
                    if(max_file_size == '' || max_file_size == undefined){
                        max_file_size = '1MB';
                    }
                }
                if(isAjax == 'true'){
                    isAjax = true;
                }else{
                    isAjax = false;
                }

                $.ajax({
                    url: token_url,
                    type: 'POST',
                    data: {},
                    cache: false,
                    contentType: false,    //不可缺
                    processData: false,    //不可缺
                    dataType : 'json',
                    success: function (data) {
                        uploaderReadyForImg(data.uptoken, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi);
                    }
                });
            };

            var uploaderReadyForImg = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
                var uploaderForUditor = Qiniu.uploader({
                    runtimes: 'html5,flash,html4',
                    browse_button: pickfiles,     //上传按钮的ID
                    container: uploader,      //上传按钮的上级元素ID
                    drop_element: uploader,
                    max_file_size: max_file_size,         //最大文件限制
                    flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
                    dragdrop: false,
                    chunk_size: '4mb',              //分块大小
                    //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
                    uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
                    // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
                    domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
                    multi_selection: multi,         //是否允许同时选择多文件
                    filters: {
                        mime_types: [               //文件类型过滤，这里限制为图片类型
                            {title: "Image files", extensions: extensions}
                        ]
                    },
                    auto_start: true,
                    unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
                    init: {
                        'FilesAdded': function (up, files) {
                            plupload.each(files, function(file) {
                                // 文件添加进队列后，处理相关的事情
                                if(typeof TOTAL_IMG != 'undefined') {
                                    if (COUNT_IMG >= TOTAL_IMG) {
                                        layer.msg('最多上传' + TOTAL_IMG + '张');
                                        up.removeFile(file);
                                        return;
                                    }
                                    COUNT_IMG ++;
                                    console.log('增加到：' + COUNT_IMG);
                                }
                            });
                        },
                        'BeforeUpload': function (up, file) {
                            // 每个文件上传前，处理相关的事情
                            layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                        },
                        'UploadProgress': function (up, file) {
                            //文件上传时，处理相关的事情

                            //上传进度 class="layui-btn" type="button"

                            //console.log(file.percent + "%");
                        },
                        'UploadComplete': function () {
                            //do something
                        },
                        'FileUploaded': function (up, file, info) {
                            //每个文件上传成功后,处理相关的事情,并记录到数据库
                            //其中 info 是文件上传成功后，服务端返回的json，形式如
                            //{
                            //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                            //  "key": "gogopher.jpg"
                            //}
                            var domain = up.getOption('domain');
                            var res = eval('(' + info.response + ')');
                            var sourceLink = domain + res.key;//获取上传文件的链接地址
                            //console.log(sourceLink);
                            $.ajax({
                                url: record_url,
                                type: 'POST',
                                data: {
                                    'imgUrl': sourceLink
                                },
                                cache: false,
                                dataType: 'json',
                                success: function (data) {
                                    layer.closeAll('loading'); // 关闭loading
                                    if (data.code === '1') {
                                        //if(multi) {  // 多图
                                            //
                                        //} else {
                                            // 单图
                                            var html = '';
                                            html += '<li class="layer-img">';
                                                html += '<a href="'+ sourceLink +'" target="_blank"><img layer-src="'+ sourceLink +'" src="'+ sourceLink +'" alt="图片" ></a>';
                                                html += '<div class="operate">';
                                                    html += '<div class="check"><input type="checkbox" name="detection_img" lay-filter="choose" lay-skin="primary" title=""></div>';
                                                    html += '<i class="layui-icon img_del">&#xe640;</i>';
                                                html += '</div>';
                                            html += '</li>';

                                            $('#Images').prepend(html);
                                            // 设置图片的高度
                                            $("#Images li img").height($("#Images li img").width());
                                            form.render("checkbox");

                                            // 添加检测报告
                                            var detections_elm = $(parent.window.frames[0].document).find('.detections');
                                            var detections = detections_elm.val();
                                            if(detections){
                                                detections = detections + ',' + sourceLink;
                                            }else{
                                                detections = sourceLink;
                                            }

                                            detections_elm.val(detections);
                                        //}
                                    }
                                }
                            });

                        },
                        'Error': function (up, err, errTip) {
                            layer.closeAll('loading'); // 关闭loading
                            alert(errTip);
                        },
                    }
                });
            };


            return {
                init: function() {
                    initUploader();
                }

            };

        }();

        UploadFile.init();


        /**
         * 删除图片
         * 删除记录数据及七牛空间中的图片
         */
        $(document).find('#Images').on('click', '.img_del', function(){
            var _this = $(this);
            layer.confirm('确定要删除吗？',{icon:3, title:'提示信息'},function(index){
                layer.close(index);

                var img_url = _this.parents('li').find('img').attr('src'); // 图片地址
                var element = _this.parents('li'); // 要删除元素
                var delimage_url = $('.delimage_url').val();
                /*
                $.ajax({
                    url: delimage_url,
                    type: 'POST',
                    data: {
                        'imgUrl' : img_url,
                    },
                    cache: false,
                    dataType : 'json',
                    success: function (data) {
                        if(data.code === '1') {
                            element.hide(1000);
                            setTimeout(function(){element.remove();},950);
                            layer.msg('删除成功');
                            if(typeof TOTAL_IMG != 'undefined') {
                                COUNT_IMG --;
                                console.log('减少到:' + COUNT_IMG);
                            }

                            // 删除检测报告
                            var detections_elm = $(parent.window.frames[0].document).find('.detections');
                            var detections = detections_elm.val();
                            var arr = detections.split(',');
                            var new_detections = '';
                            for(var i = 0; i < arr.length; i++){
                                if(arr[i] != img_url){
                                    new_detections += ',' + arr[i];
                                }
                            }

                            detections_elm.val(new_detections.substr(1));
                        } else{
                            layer.msg('删除失败');
                        }
                    }
                });
                */
                element.hide(1000);
                setTimeout(function(){element.remove();},950);
                layer.msg('删除成功');
                if(typeof TOTAL_IMG != 'undefined') {
                    COUNT_IMG --;
                    console.log('减少到:' + COUNT_IMG);
                }

                // 删除检测报告
                var detections_elm = $(parent.window.frames[0].document).find('.detections');
                var detections = detections_elm.val();
                var arr = detections.split(',');
                var new_detections = '';
                for(var i = 0; i < arr.length; i++){
                    if(arr[i] != img_url){
                        new_detections += ',' + arr[i];
                    }
                }

                detections_elm.val(new_detections.substr(1));
            });
        });
    });
</script>
{/block}